<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.phone"
        clearable
        class="filter-item"
        style="width: 150px;"
        placeholder="请输入手机号"
      />
      <el-input
        v-model="listQuery.cardNo"
        clearable
        class="filter-item"
        style="width: 150px;"
        placeholder="请输入会员卡号"
      />
      <el-input
        v-model="listQuery.cardOrderNo"
        clearable
        class="filter-item"
        style="width: 150px;"
        placeholder="请输入订单号"
      />
      <el-select
        v-model="listQuery.status"
        clearable
        style="width: 150px"
        class="filter-item"
        placeholder="请选择订单状态"
      >
        <el-option v-for="(key, value) in statusMap" :key="key" :label="key" :value="value" />
      </el-select>
      <el-select
        v-model="listQuery.storeId"
        clearable
        style="width: 200px"
        class="filter-item"
        placeholder="请选择门店" >
        <el-option v-for="(item,index) in storeList" :key="index" :label="item.storeName" :value="item.id" />
      </el-select>
      <el-date-picker
        v-model="downData.gmtStart"
        type="datetime"
        style="width: 200px"
        class="filter-item"
        default-time="00:00:00"
        placeholder="选择开始日期"
      />
      <template>至</template>
      <el-date-picker
        v-model="downData.gmtEnd"
        type="datetime"
        style="width: 200px"
        class="filter-item"
        default-time="23:59:59"
        placeholder="选择结束日期"
      />
      <el-button
        v-permission="['promote:cardorder:query']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >查找</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
      style="white-space: pre-line"
    >
      <el-table-column prop="id" align="center" label="序号"/>
      <el-table-column align="center" width="100" label="订单状态" prop="status">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.status | orderStatusFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="cardOrderNo" width="200" align="center" label="储值卡订单号"/>
      <el-table-column prop="actualPrice" align="center" label="实付金额">
        <template slot-scope="scope">
          <span>{{ scope.row.actualPrice | priceCheck }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="payPrice" align="center" label="支付金额">
        <template slot-scope="scope">
          <span>{{ scope.row.payPrice | priceCheck }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="payId" align="center" label="支付码"/>
      <el-table-column prop="payChannel" width="100" align="center" label="支付渠道">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.payChannel | payChannelFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="gmtPsy" align="center" label="支付时间">
        <template slot-scope="scope">{{ scope.row.gmtPsy | timeFormate }}</template>
      </el-table-column>
      <el-table-column prop="cardUserName" align="center" label="绑卡用户名称"/>
      <el-table-column prop="cardUserId" align="center" label="卡绑定用户id"/>
      <el-table-column prop="cardPhone" align="center" label="绑卡手机号"/>
      <el-table-column prop="operType" align="center" label="操作类型   1:匿名激活卖卡 2:绑定卖卡"/>
      <el-table-column prop="storeId" align="center" label="门店id"/>
      <el-table-column prop="storeUserId" align="center" label="收银员id"/>
      <el-table-column prop="paymentPrice" align="center" label="用户实际支付金额">
        <template slot-scope="scope">
          <span>{{ scope.row.paymentPrice | priceCheck }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="changePrice" align="center" label="找零">
        <template slot-scope="scope">
          <span>{{ scope.row.changePrice | priceCheck }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="smallPrice" align="center" label="抹零">
        <template slot-scope="scope">
          <span>{{ scope.row.smallPrice | priceCheck }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="remarks" align="center" label="备注信息"/>
      <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-permission="['promote:cardorder:cardOrderDetail']"
            class="filter-item"
            type="primary"
            @click="getCardOrderDetail(scope.row)"
          >查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 查看详情对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="订单来源: " width="200" prop="channel">
          <template>
            <span>{{ cardOrderDetail.channel }}</span>
          </template>
        </el-form-item>
        <el-form-item label="订单状态: " width="200" prop="status">
          <template>
            <span>{{ cardOrderDetail.status | orderStatusFilter }}</span>
          </template>
        </el-form-item>
        <el-form-item label="退单状态: " width="200" prop="sonStatus">
          <template>
            <span>{{ cardOrderDetail.sonStatus }}</span>
          </template>
        </el-form-item>
        <el-form-item label="储值卡订单号: " width="200" prop="cardOrderNo">
          <template>
            <span>{{ cardOrderDetail.cardOrderNo }}</span>
          </template>
        </el-form-item>
        <el-form-item label="实付金额: " width="200" prop="actualPrice">
          <template>
            <span>{{ cardOrderDetail.actualPrice | priceCheck }}</span>
          </template>
        </el-form-item>
        <el-form-item label="支付金额: " width="200" prop="payPrice">
          <template>
            <span>{{ cardOrderDetail.payPrice | priceCheck }}</span>
          </template>
        </el-form-item>
        <el-form-item label="支付码: " width="200" prop="payId">
          <template>
            <span>{{ cardOrderDetail.payId }}</span>
          </template>
        </el-form-item>
        <el-form-item label="支付渠道: " width="200" prop="payChannel">
          <template>
            <span>{{ cardOrderDetail.payChannel | payChannelFilter }}</span>
          </template>
        </el-form-item>
        <el-form-item label="支付时间: " width="200" prop="gmtPsy">
          <template>
            <span>{{ cardOrderDetail.gmtPsy | timeFormate }}</span>
          </template>
        </el-form-item>
        <el-form-item label="绑卡用户名称: " width="200" prop="cardUserName">
          <template>
            <span>{{ cardOrderDetail.cardUserName }}</span>
          </template>
        </el-form-item>
        <el-form-item label="卡绑定用户id: " width="200" prop="cardUserId">
          <template>
            <span>{{ cardOrderDetail.cardUserId }}</span>
          </template>
        </el-form-item>
        <el-form-item label="绑卡手机号: " width="200" prop="cardPhone">
          <template>
            <span>{{ cardOrderDetail.cardPhone }}</span>
          </template>
        </el-form-item>
        <el-form-item label="操作类型: " width="200" prop="operType">
          <template>
            <span>{{ cardOrderDetail.operType }}</span>
          </template>
        </el-form-item>
        <el-form-item label="门店id: " width="200" prop="storeId">
          <template>
            <span>{{ cardOrderDetail.storeId }}</span>
          </template>
        </el-form-item>
        <el-form-item label="收银员id: " width="200" prop="storeUserId">
          <template>
            <span>{{ cardOrderDetail.storeUserId }}</span>
          </template>
        </el-form-item>
        <el-form-item label="用户实际支付金额: " width="200" prop="paymentPrice">
          <template>
            <span>{{ cardOrderDetail.paymentPrice | priceCheck }}</span>
          </template>
        </el-form-item>
        <el-form-item label="找零: " width="200" prop="changePrice">
          <template>
            <span>{{ cardOrderDetail.changePrice | priceCheck }}</span>
          </template>
        </el-form-item>
        <el-form-item label="抹零: " width="200" prop="smallPrice">
          <template>
            <span>{{ cardOrderDetail.smallPrice | priceCheck }}</span>
          </template>
        </el-form-item>
        <el-form-item label="备注信息: " width="200" prop="remarks">
          <template>
            <span>{{ cardOrderDetail.remarks }}</span>
          </template>
        </el-form-item>
        <el-form-item label="商品信息">
          <el-table :data="cardOrderDetail.cardDetails" size="small" border fit highlight-current-row>
            <el-table-column align="center" label="会员卡号" prop="cardNo" />
            <el-table-column align="center" label="会员卡额度" prop="cardQuota" />
            <el-table-column align="center" label="总价" prop="totalCardPrice" >
              <template slot-scope="scope">
                <span>{{ scope.row.totalCardPrice | priceCheck }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<style>
.el-table .cell {
  white-space: pre-line;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>

<script>
import { list, create, del, update, active, cardOrderDetail} from '@/api/cardorder'
import { listStoresByPara } from '@/api/store'
import { formatGmt } from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

const statusMap = {
  10: '未付款',
  50: '已完成',
  60: '退款中',
  70: '已退款',
  71: '部分退款',
  80: '已取消',
  90: '已取消(系统)'
}

const payChannelMap = {
  WX: '微信支付',
  OFFLINE: '线下支付',
  ALI: '支付宝支付',
  CASH: '现金支付',
  BALANCE: '会员余额支付',
  BANKCARD: '银行卡支付'
}

export default {
  name: 'CardOrder',
  components: { Pagination },
  filters: {
    orderStatusFilter(status) {
      return statusMap[status]
    },
    priceCheck(price) {
      if (price === '' || price === null || price === undefined) {
        return 0
      }
      return (price / 100.0).toFixed(2)
    },
    payChannelFilter(channel) {
      const str = payChannelMap[channel]
      if (str) {
        return str
      }
      return '未支付'
    },
    timeFormate(time) {
      if (time === '' || time === undefined || time === null) {
        return '无数据'
      }
      return formatGmt(time)
    }
  },
  data() {
    return {
      list: undefined,
      statusMap,
      storeList: [],
      listQuerystore: {
        status: undefined
      },
      total: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        limit: 20,
        status: undefined,
        startTime: undefined,
        endTime: undefined
      },
      downData: {
        status: '',
        gmtStart: undefined,
        gmtEnd: undefined
      },
      cardOrderDetail: {},
      options: [],
      dataForm: {
        id: undefined
      },
      detailQuery: {
        orderId: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建',
        view: '详情'
      },
      rules: {}
    }
  },
  created() {
    this.getList()
    this.listStoresByPara()
  },
  methods: {
    getList() {
      this.listLoading = true
      this.listQuery.startTime = this.formatDateyMdhms(this.downData.gmtStart, 'yyyy-MM-dd hh:mm:ss')
      this.listQuery.endTime = this.formatDateyMdhms(this.downData.gmtEnd, 'yyyy-MM-dd hh:mm:ss')
      list(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined
      }
    },
    handleStatus(row) {
      this.resetForm()
      this.dataForm.id = row.id
      this.dataForm.status = row.status === 1 ? 0 : 1
      active(this.dataForm)
        .then(res => {
          this.$notify.success({
            title: '成功',
            message: '状态更改成功'
          })
          this.getList()
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      create(this.dataForm)
        .then(response => {
          this.getList()
          this.dialogFormVisible = false
          this.$notify.success({
            title: '成功',
            message: '创建成功'
          })
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: '失败'
          })
        })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      update(this.dataForm)
        .then(response => {
          this.getList()
          this.dialogFormVisible = false
          this.$notify.success({
            title: '成功',
            message: '更新成功'
          })
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: '失败'
          })
        })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: '失败'
            })
          })
      }).catch(() => {
        return false
      })
    },
    formatDateyMdhms(timestamp, format) {
      if (timestamp === null || timestamp === undefined) {
        return
      }
      var dateTime = new Date(timestamp)
      var date = {
        'M+': dateTime.getMonth() + 1,
        'd+': dateTime.getDate(),
        'h+': dateTime.getHours(),
        'm+': dateTime.getMinutes(),
        's+': dateTime.getSeconds(),
        'q+': Math.floor((dateTime.getMonth() + 3) / 3),
        'S+': dateTime.getMilliseconds()
      }
      if (/(y+)/i.test(format)) {
        format = format.replace((RegExp.$1).toString(), ((dateTime.getFullYear() + '').substr(4 - RegExp.$1.length)).toString())
      }
      for (var k in date) {
        if (new RegExp('(' + k + ')').test(format)) {
          format = format.replace((RegExp.$1).toString(), (RegExp.$1.length === 1
            ? date[k] : ('00' + date[k]).substr(('' + date[k]).length)).toString())
        }
      }
      return format
    },
    getCardOrderDetail(row) {
      this.dialogStatus = 'view'
      this.dialogFormVisible = true
      this.detailQuery.orderId = row.id
      cardOrderDetail(this.detailQuery)
        .then(response => {
          this.cardOrderDetail = response.data.data
        })
        .catch(response => {
          this.$notify.error({
            title: '异常',
            message: '数据查询异常'
          })
        })
    },
    listStoresByPara() {
      this.listQuerystore.status = 1
      listStoresByPara(this.listQuerystore)
        .then(response => {
          this.storeList = response.data.data
        })
        .catch(() => {
          this.storeList = []
        })
    }
  }
}
</script>

